/**
 * 
 */
package com.base.web.interceptor;



import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * spring mvc Monitor 监控 拦截器
 * @author leiruiqi
 *
 */
public class BaseMonitorInterceptor extends HandlerInterceptorAdapter {

	protected static Logger logger = LoggerFactory.getLogger(BaseMonitorInterceptor.class);
	
	protected static final ThreadLocal<Long> startTimeThreadLocal = new ThreadLocal<Long>();
	
	public BaseMonitorInterceptor() {
		//CalClientInternalFacade.getCalClientInternalFacade().init();
	}
	
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		long startTime = System.currentTimeMillis();
		startTimeThreadLocal.set(startTime);
		return super.preHandle(request, response, handler);
	}
	
	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		super.postHandle(request, response, handler, modelAndView);
	}
	
	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		/*if(CalClientInternalFacade.getCalClientInternalFacade().isCalEnabled()) {
			long startTime = startTimeThreadLocal.get();
			long costTime = System.currentTimeMillis() - startTime;
			CalStatisticTargetWrapper calStatisticTargetWrapper = CalClientInternalFacade.getCalClientInternalFacade().handleForWebFilter(request, ex, costTime);
			if(null!=ex){
				String errorMessageWithDetailInfo = CalUtils.getErrorMessageWithDetailInfo(ex, calStatisticTargetWrapper);
				logger.error("CalFilter catched Exception. Details: {}",errorMessageWithDetailInfo);
			}
		}*/
		HandlerMethod handlerMethod=(HandlerMethod) handler;
		String beanName = handlerMethod.getBeanType().getName();
		String methodName = handlerMethod.getMethod().getName();

		long startTime = startTimeThreadLocal.get();
		long costTime = System.currentTimeMillis() - startTime;
		if(null!=ex){
			logger.error("CalFilter catched Exception. Details: {}",ex);
		}
		if(logger.isInfoEnabled()){
			logger.info("cal interceptor cost `"+costTime+"`"+beanName+"`"+methodName);
		}
		
		super.afterCompletion(request, response, handler, ex);
	}
	
	
}
